﻿using AutoMapper;
using MediatR;
using MES.Process.API.Application.Command.工艺命令;
using MES.Process.Domain;
using MES.Process.ErrorCode;
using MES.Process.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace MES.Process.API.Application.CommandHandler.工艺命令处理
{
    /// <summary>
    /// 工艺填加命令处理器
    /// </summary>
    public class CraftsAddCommandHandler : IRequestHandler<CraftsAddCommand, APIResult<int>>
    {
        private readonly ILogger<CraftsAddCommandHandler> _logger;
        private readonly IBaseRepository<Domain.Crafts> _craftsRepository;
        private readonly IMapper mapper;
        private readonly IBaseRepository<Craft_Process> cpRepository;
        public CraftsAddCommandHandler(ILogger<CraftsAddCommandHandler> logger, IBaseRepository<Domain.Crafts> craftsRepository = null, IMapper mapper = null, IBaseRepository<Craft_Process> cpRepository = null)
        {
            _logger = logger;
            _craftsRepository = craftsRepository;
            this.mapper = mapper;
            this.cpRepository = cpRepository;
        }

        public async Task<APIResult<int>> Handle(CraftsAddCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var modle = mapper.Map<Domain.Crafts>(request);
                var exists = await _craftsRepository.GetValues()
                    .AnyAsync(x => x.CraftsCode == request.CraftsCode, cancellationToken);
                if (exists)
                {
                    result.Code = APIEnums.Fail;
                    result.Message = "工艺编号已存在，请重新输入";
                    return result;
                }
                if (!string.IsNullOrEmpty(request.Pidlist))
                {
                    modle.HaveProcess = request.Pidlist.Split(',').Select(x => int.Parse(x)).Count();
                }
                else 
                {
                    modle.HaveProcess = 0;
                }
                    
                using (var ts = await _craftsRepository._context.Database.BeginTransactionAsync(cancellationToken)) 
                {
                    try
                    {
                        int index=0;
                        var r= await _craftsRepository.AddAsync(modle);
                        int id = modle.ID; // SaveChanges 后会回填自增主键
                        if (!string.IsNullOrEmpty(request.Pidlist)) 
                        {
                            List<Craft_Process> craft_Processes = request.Pidlist
                            .Split(',')
                            .Select(pidStr =>
                            {
                                index++;
                                return new Craft_Process
                                {
                                    CraftsId = id,
                                    ProcessId = int.Parse(pidStr),
                                    StepId = index
                                };
                            }).ToList();
                            await cpRepository.AddRangeAsync(craft_Processes);
                        }
                        
                        //List<Craft_Process> craft_Processes = new List<Craft_Process>();
                        //foreach (var process in craft_Processes) 
                        //{
                        //    process.CraftsId = id;
                        //    foreach (var item in pidList)
                        //    {
                        //        process.ProcessId = item;
                        //    }
                        //    craft_Processes.Add(process);
                        //}

                       
                        await ts.CommitAsync(cancellationToken);
                        result.Code = APIEnums.Success;
                        result.Message = "添加成功";
                        result.Data = r;
                    }
                    catch (Exception ex)
                    {
                        await ts.RollbackAsync(cancellationToken);
                    }
                    
                    return result;
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
